/**
 * Title: NewsItem.java
 * Description:
 * author: kotomifi
 * date: Jul 15, 2014
 * ©2014 apping 社区
 */
package com.apping.demo.bbs;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.apping.demo.bbs.bean.Comment;
import com.apping.demo.bbs.bean.CommentJson;
import com.apping.demo.bbs.bean.CommentMsgComment;
import com.apping.demo.bbs.bean.NewsInfo;
import com.apping.demo.bbs.bean.NewsJson;
import com.apping.demo.bbs.utils.DBUtil;
import com.apping.demo.bbs.utils.DateUtil;
import com.apping.demo.bbs.utils.HttpTools;
import com.apping.demo.bbs.utils.NetCheck;
import com.apping.demo.bbs.utils.SignatureUtil;
import com.sina.weibo.sdk.demo.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 *
 */
public class NewsItemPage extends Activity {

	private TextView newsTitle;
	private TextView newsAuthor;
	private TextView newsTime;
	private TextView newsContent;
	private ListView newsComment;
	private Button commentBtn;
	
	private SQLiteDatabase db;
	private CommentAdapter adapter;
	ArrayList<HashMap<String, Object>>listItem;
	
	private long newsId;
	private NewsJson newsJson = null;
	private CommentJson commentJson = null;
	private List<CommentMsgComment> comments = new ArrayList<CommentMsgComment>();
	
	
	String mComment = "";
	long uid;
	String author;
	
	private static final int LOAD_NEWS_FINISH = 0;
	private static final int POST_COMMENT = 1;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case LOAD_NEWS_FINISH:
				initUI();
				break;
			case POST_COMMENT:
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_item);
		db = SQLiteDatabase.openOrCreateDatabase(
				Environment.getExternalStorageDirectory().toString() + "/news.db", null);
		setNewsId();
		getNews();
		setOverflowShowingAlways();
	}
	
	public void setNewsId() {
		Bundle bundle = getIntent().getExtras();
		newsId = bundle.getLong("newsId");
	}
	
	public void initUI() {
		String title = newsJson.getMsg().getTitle();
		author = newsJson.getMsg().getAuthor();
		long time = newsJson.getMsg().getTime();
		String content = newsJson.getMsg().getContent();
		
		newsTitle = (TextView)findViewById(R.id.news_title);
		newsTitle.setText(title);
		
		newsAuthor = (TextView)findViewById(R.id.news_author);
		newsAuthor.setText(author);
		
		newsTime = (TextView)findViewById(R.id.news_time);
		newsTime.setText(DateUtil.dateFormat(time));
		
		newsContent = (TextView)findViewById(R.id.news_content);
		newsContent.setText(content);
		
		commentBtn = (Button)findViewById(R.id.add_comment_btn);
		commentBtn.setOnClickListener(new OnClickListener() {
			final EditText commentEdit = new EditText(NewsItemPage.this);
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(NewsItemPage.this)
				.setTitle("评论")
				.setIcon(
					android.R.drawable.ic_dialog_info).setView(
						commentEdit).setPositiveButton(
							"评论", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int i) {
									mComment = commentEdit.getText().toString();
									if (mComment != "") {
										postComment();
									}
								}
							}).setNegativeButton("取消", null).show();
			}
		});
		newsComment = (ListView)findViewById(R.id.new_comment_list);
		
		adapter = new CommentAdapter(this);
		newsComment.setAdapter(adapter);
	}
	
	/**
	 * 提交评论
	 */
	public void postComment() {
		// 检查是否连接到网络
		if (NetCheck.isNetworkConnected(this)) {
			new Thread() {
				@Override
				public void run() {
					String url = "http://42.96.192.37:8080/apping/demo/post_comment";
					////////////////////////////////////////////////////
					uid = 1;
					String ticket = "bd637611abfe504f1ad40547af91687f";
					String signature = SignatureUtil.getSignature(
							mComment,
							String.valueOf(uid),
							ticket,
							author,
							String.valueOf(newsId));
					
					/////////////////////////////////////////////////
					String param = "";
					param = "author=" + author +
							"&comment=" + mComment +
							"&news_id=" + newsId + 
							"&signature=" + signature +
							"&uid=1";
					byte[] data = param.getBytes();
					HttpTools httpTools = new HttpTools();
					httpTools.post(url, data);
					Log.i("Response:", httpTools.getContent());
					handler.sendEmptyMessage(POST_COMMENT);
				}
			}.start();
		} else {
			Toast.makeText(NewsItemPage.this, 
					"无法连接到网络,请检查网络连接", 2000).show();
		}
	}
	
	public class ViewHolder {
		public ImageView avatar;
		public TextView name;
		public TextView time;
		public TextView content;
	}
	
	public class CommentAdapter extends BaseAdapter {
		
		private LayoutInflater mInflater = null;

		public CommentAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			return comments.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.comment_item, null);
                holder = new ViewHolder();
                holder.avatar = (ImageView)convertView.findViewById(R.id.comment_avatar);
                holder.name = (TextView)convertView.findViewById(R.id.comment_name);
                holder.time = (TextView)convertView.findViewById(R.id.comment_time);
                holder.content = (TextView)convertView.findViewById(R.id.comment_content);
                convertView.setTag(holder);
                Log.i("empty", "em");
            } else {
                holder = (ViewHolder)convertView.getTag();
                Log.i("empty", "mm");
            }
            holder.avatar.setImageResource(R.drawable.ic_default_avatar);
            holder.name.setText(comments.get(position).getAuthor());
            holder.time.setText(DateUtil.dateFormat(comments.get(position).getTime()));
            holder.content.setText(comments.get(position).getContent());
            return convertView;
        }
	}
	
	/**
	 * 根据newsId获取news和comments
	 */
	public void getNews() {
		// 检查是否连接到网络
		if (NetCheck.isNetworkConnected(this)) {
			new Thread() {
				@Override
				public void run() {
					HttpTools httpTools = new HttpTools();
					
					///////////////////////////////////////////////////////
					long uid = 1;
					String ticket = "bd637611abfe504f1ad40547af91687f";
					
					String signature = SignatureUtil.getSignature(
							String.valueOf(uid),
							String.valueOf(newsId),
							ticket);
					String newsPath = "http://42.96.192.37:8080/apping/demo/news?"
							+ "uid=" + uid
							+ "&&signature=" + signature
							+ "&&news_id=" + String.valueOf(newsId);
					///////////////////////////////////////////////////////
					try {
						httpTools.get(newsPath);
					} catch (Exception e) {
						e.printStackTrace();
					}
					String jsonStr = httpTools.getContent();
					String rst = JSON.parseObject(jsonStr).getString("rst");
					if (rst.equals("SUCCESS")) {
						newsJson = JSON.parseObject(jsonStr, NewsJson.class);
						// 获取评论列表
						String commentUrl = "http://42.96.192.37:8080/apping/demo/comment?" 
								+ "uid=" + uid
								+ "&&signature=" + signature
								+ "&&news_id=" + String.valueOf(newsId);
						try {
							httpTools.get(commentUrl);
						} catch (Exception e) {
							e.printStackTrace();
						}
						String commentStr = httpTools.getContent();
						String commentRst = JSON.parseObject(commentStr).getString("rst");
						if (commentRst.equals("SUCCESS")) {
							Log.i("str", commentStr);
							commentJson = JSON.parseObject(commentStr, CommentJson.class);
							comments = commentJson.getMsg().getComments();
							DBUtil mDb = new DBUtil(db);
							List<Comment> tempComments = new ArrayList<Comment>();
							for (int j = 0; j < comments.size(); j++) {
								Comment temp = new Comment();
								temp.setNewsId(newsId);
								temp.setAuthor(comments.get(j).getAuthor());
								temp.setTime(comments.get(j).getTime());
								temp.setContent(comments.get(j).getContent());
							}
							mDb.insert(tempComments);
						} else {
							Toast.makeText(NewsItemPage.this, 
									"获取评论失败", 2000).show();
						}
						
						// 添加记录到数据库
//						NewsInfo newsInfo = new NewsInfo();
//						newsInfo.setAuthor(newsJson.getMsg().getAuthor());
//						newsInfo.setContent(newsJson.getMsg().getContent());;
//						newsInfo.setId(newsJson.getMsg().getId());
//						newsInfo.setStar(newsJson.getMsg().getStar());
//						newsInfo.setTime(newsJson.getMsg().getTime());
//						newsInfo.setTitle(newsJson.getMsg().getTitle());
//						DBUtil mDb = new DBUtil(db);
//						mDb.insert(newsInfo);

						handler.sendEmptyMessage(LOAD_NEWS_FINISH);
					} else {
						Toast.makeText(NewsItemPage.this, 
								"网络不给力呀", 2000).show();
					}
				}
			}.start();
		} else {
			Toast.makeText(NewsItemPage.this, 
					"无法连接到网络，请检查网络连接", 2000).show();
		}
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_activity_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_plus:
			return true;
		case R.id.about:
			Intent intent = new Intent();
			intent.setClass(NewsItemPage.this, About.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}
	
	/**
	 * 让不同设备都可以显示Overflow 菜单
	 */
	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
